"""
需要导入第三方模块
cmd控制台输入以下命令并执行：
pip install scikit-learn
pip install numpy
pip install matplotlib
"""

# 导入必要的库
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, classification_report
import matplotlib.pyplot as plt
import numpy as np
# 加载手写数字数据集
digits = load_digits()
X = digits.data  # 特征数据（图像像素值）
y = digits.target  # 标签数据（对应的数字）

# 划分训练集和测试集，测试集占比 20%
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化 KNN 分类器，这里先假设 K = 5
knn = KNeighborsClassifier(n_neighbors=5)

# 训练模型
knn.fit(X_train, y_train)

# 进行预测
y_pred = knn.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型的准确率: {accuracy * 100:.2f}%")

# 打印分类报告，包含精确率、召回率、F1 值等信息
print("分类报告:")
print(classification_report(y_test, y_pred))

# 可视化一些预测结果
fig, axes = plt.subplots(2, 5, figsize=(10, 4))
axes = axes.flatten()
for i in range(10):
    # 随机选择一个测试样本
    idx = np.random.randint(0, len(X_test))
    img = X_test[idx].reshape(8, 8)
    axes[i].imshow(img, cmap=plt.cm.gray_r)
    axes[i].set_title(f"True: {y_test[idx]}, Pred: {y_pred[idx]}")
    axes[i].axis('off')

plt.tight_layout()
plt.show()